<template>
  <div class="room-list">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>房间管理</h2>
    </div>

    <!-- 查询条件 -->
    <div class="search-form">
      <el-form :model="searchForm" inline>
        <el-form-item label="房间号">
          <el-input
            v-model="searchForm.roomNumber"
            placeholder="请输入房间号"
            clearable
            style="width: 150px"
          />
        </el-form-item>
        <el-form-item label="房间类型">
          <el-select
            v-model="searchForm.type"
            placeholder="请选择房间类型"
            clearable
            style="width: 150px"
          >
            <el-option label="单人间" value="SINGLE" />
            <el-option label="双人间" value="DOUBLE" />
            <el-option label="多人间" value="MULTIPLE" />
            <el-option label="VIP房间" value="VIP" />
          </el-select>
        </el-form-item>
        <el-form-item label="楼层">
          <el-input-number
            v-model="searchForm.floor"
            :min="1"
            :max="20"
            placeholder="楼层"
            style="width: 120px"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            clearable
            style="width: 120px"
          >
            <el-option label="可用" value="AVAILABLE" />
            <el-option label="占用" value="OCCUPIED" />
            <el-option label="维护中" value="MAINTENANCE" />
            <el-option label="停用" value="DISABLED" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作按钮 -->
    <div class="table-toolbar">
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        新增房间
      </el-button>
      <el-button
        type="danger"
        :disabled="selectedIds.length === 0"
        @click="handleBatchDelete"
      >
        <el-icon><Delete /></el-icon>
        批量删除
      </el-button>
      <el-button type="success" @click="handleViewAvailable">
        <el-icon><View /></el-icon>
        查看可用房间
      </el-button>
    </div>

    <!-- 房间表格 -->
    <el-table
      v-loading="loading"
      :data="roomList"
      @selection-change="handleSelectionChange"
      stripe
      border
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="roomNumber" label="房间号" width="100" />
      <el-table-column prop="type" label="房间类型" width="100">
        <template #default="{ row }">
          <el-tag :type="getRoomTypeTagType(row.type)">
            {{ getRoomTypeText(row.type) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="floor" label="楼层" width="80" />
      <el-table-column prop="capacity" label="容量" width="80" />
      <el-table-column prop="currentOccupancy" label="当前入住" width="100" />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="getRoomStatusTagType(row.status)">
            {{ getRoomStatusText(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="price" label="价格/天" width="100">
        <template #default="{ row }">
          ¥{{ row.price }}
        </template>
      </el-table-column>
      <el-table-column prop="facilities" label="设施" width="200" show-overflow-tooltip />
      <el-table-column prop="description" label="描述" width="200" show-overflow-tooltip />
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="handleEdit(row)">
            编辑
          </el-button>
          <el-button type="info" size="small" @click="handleView(row)">
            详情
          </el-button>
          <el-button type="danger" size="small" @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.size"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 房间表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="700px"
      @close="handleDialogClose"
    >
      <el-form
        ref="roomFormRef"
        :model="roomForm"
        :rules="roomRules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="房间号" prop="roomNumber">
              <el-input v-model="roomForm.roomNumber" placeholder="请输入房间号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="房间类型" prop="type">
              <el-select v-model="roomForm.type" placeholder="请选择房间类型" style="width: 100%">
                <el-option label="单人间" value="SINGLE" />
                <el-option label="双人间" value="DOUBLE" />
                <el-option label="多人间" value="MULTIPLE" />
                <el-option label="VIP房间" value="VIP" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="楼层" prop="floor">
              <el-input-number
                v-model="roomForm.floor"
                :min="1"
                :max="20"
                placeholder="请输入楼层"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="容量" prop="capacity">
              <el-input-number
                v-model="roomForm.capacity"
                :min="1"
                :max="10"
                placeholder="请输入容量"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="价格/天" prop="price">
              <el-input-number
                v-model="roomForm.price"
                :min="0"
                :precision="2"
                placeholder="请输入价格"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="roomForm.status" placeholder="请选择状态" style="width: 100%">
                <el-option label="可用" value="AVAILABLE" />
                <el-option label="占用" value="OCCUPIED" />
                <el-option label="维护中" value="MAINTENANCE" />
                <el-option label="停用" value="DISABLED" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="设施" prop="facilities">
          <el-input
            v-model="roomForm.facilities"
            placeholder="请输入房间设施，用逗号分隔"
          />
        </el-form-item>

        <el-form-item label="描述">
          <el-input
            v-model="roomForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入房间描述（可选）"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Delete, View } from '@element-plus/icons-vue'
import {
  getRoomList,
  createRoom,
  updateRoom,
  deleteRoom,
  batchDeleteRooms,
  getAvailableRooms
} from '@/api/room'

// 响应式数据
const loading = ref(false)
const roomList = ref([])
const selectedIds = ref([])
const dialogVisible = ref(false)
const dialogTitle = ref('')
const roomFormRef = ref()

// 搜索表单
const searchForm = reactive({
  roomNumber: '',
  type: '',
  floor: null,
  status: ''
})

// 分页信息
const pagination = reactive({
  page: 1,
  size: 10,
  total: 0
})

// 房间表单
const roomForm = reactive({
  id: null,
  roomNumber: '',
  type: '',
  floor: null,
  capacity: null,
  price: null,
  status: 'AVAILABLE',
  facilities: '',
  description: ''
})

// 表单验证规则
const roomRules = {
  roomNumber: [
    { required: true, message: '请输入房间号', trigger: 'blur' },
    { min: 1, max: 20, message: '房间号长度在 1 到 20 个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择房间类型', trigger: 'change' }
  ],
  floor: [
    { required: true, message: '请输入楼层', trigger: 'blur' },
    { type: 'number', min: 1, max: 20, message: '楼层必须在1-20之间', trigger: 'blur' }
  ],
  capacity: [
    { required: true, message: '请输入容量', trigger: 'blur' },
    { type: 'number', min: 1, max: 10, message: '容量必须在1-10之间', trigger: 'blur' }
  ],
  price: [
    { required: true, message: '请输入价格', trigger: 'blur' },
    { type: 'number', min: 0, message: '价格必须大于等于0', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 获取房间列表
const fetchRoomList = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page - 1,
      size: pagination.size,
      ...searchForm
    }
    const response = await getRoomList(params)
    roomList.value = response.data.content || []
    pagination.total = response.data.totalElements || 0
  } catch (error) {
    ElMessage.error('获取房间列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  fetchRoomList()
}

// 重置搜索条件
const handleReset = () => {
  Object.assign(searchForm, {
    roomNumber: '',
    type: '',
    floor: null,
    status: ''
  })
  pagination.page = 1
  fetchRoomList()
}

// 新增房间
const handleAdd = () => {
  dialogTitle.value = '新增房间'
  resetRoomForm()
  dialogVisible.value = true
}

// 编辑房间
const handleEdit = (row) => {
  dialogTitle.value = '编辑房间'
  Object.assign(roomForm, { ...row })
  dialogVisible.value = true
}

// 查看房间详情
const handleView = (row) => {
  ElMessage.info('查看房间详情功能待实现')
}

// 查看可用房间
const handleViewAvailable = async () => {
  try {
    const response = await getAvailableRooms()
    const availableRooms = response.data || []
    ElMessage.success(`当前有 ${availableRooms.length} 个可用房间`)
    // 可以在这里显示可用房间列表或跳转到专门的页面
  } catch (error) {
    ElMessage.error('获取可用房间失败')
  }
}

// 删除房间
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除房间 "${row.roomNumber}" 吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    await deleteRoom(row.id)
    ElMessage.success('删除成功')
    fetchRoomList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 批量删除
const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedIds.value.length} 个房间吗？`,
      '批量删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    await batchDeleteRooms(selectedIds.value)
    ElMessage.success('批量删除成功')
    selectedIds.value = []
    fetchRoomList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除失败')
    }
  }
}

// 表格选择变化
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id)
}

// 分页大小变化
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.page = 1
  fetchRoomList()
}

// 当前页变化
const handleCurrentChange = (page) => {
  pagination.page = page
  fetchRoomList()
}

// 提交表单
const handleSubmit = async () => {
  try {
    await roomFormRef.value.validate()
    if (roomForm.id) {
      await updateRoom(roomForm.id, roomForm)
      ElMessage.success('更新成功')
    } else {
      await createRoom(roomForm)
      ElMessage.success('创建成功')
    }
    dialogVisible.value = false
    fetchRoomList()
  } catch (error) {
    if (error.message) {
      ElMessage.error('操作失败')
    }
  }
}

// 对话框关闭
const handleDialogClose = () => {
  roomFormRef.value?.resetFields()
  resetRoomForm()
}

// 重置房间表单
const resetRoomForm = () => {
  Object.assign(roomForm, {
    id: null,
    roomNumber: '',
    type: '',
    floor: null,
    capacity: null,
    price: null,
    status: 'AVAILABLE',
    facilities: '',
    description: ''
  })
}

// 获取房间类型标签类型
const getRoomTypeTagType = (type) => {
  const typeMap = {
    SINGLE: 'primary',
    DOUBLE: 'success',
    MULTIPLE: 'warning',
    VIP: 'danger'
  }
  return typeMap[type] || 'info'
}

// 获取房间类型文本
const getRoomTypeText = (type) => {
  const typeMap = {
    SINGLE: '单人间',
    DOUBLE: '双人间',
    MULTIPLE: '多人间',
    VIP: 'VIP房间'
  }
  return typeMap[type] || type
}

// 获取房间状态标签类型
const getRoomStatusTagType = (status) => {
  const statusMap = {
    AVAILABLE: 'success',
    OCCUPIED: 'warning',
    MAINTENANCE: 'info',
    DISABLED: 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取房间状态文本
const getRoomStatusText = (status) => {
  const statusMap = {
    AVAILABLE: '可用',
    OCCUPIED: '占用',
    MAINTENANCE: '维护中',
    DISABLED: '停用'
  }
  return statusMap[status] || status
}

// 组件挂载时获取数据
onMounted(() => {
  fetchRoomList()
})
</script>

<style scoped>
.room-list {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
}

.search-form {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.table-toolbar {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.el-table {
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
</style>